<template>
    <div class="qilin-image">
        <el-card>
            <QilinSearch :searchConfig.sync="searchConfig" @searchData="getTableData()">
                <template v-slot:dateRange="slotData">
                    <el-date-picker v-model="searchConfig.submitData.startTime" type="datetime"
                        placeholder="请输入开始时间" format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placement="bottom-start"
                    ></el-date-picker>
                    <span class="search-separate">-</span>
                    <el-date-picker v-model="searchConfig.submitData.endTime" type="datetime"
                        placeholder="请输入结束时间" format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placement="bottom-start"
                        default-time="23:59:59"
                    ></el-date-picker>
                </template>
            </QilinSearch>
        </el-card>
        <el-card>
            <QilinTable :tableConfig.sync="tableConfig" @changeCurrentPage="handleCurrentPage"
                @changeCurrentSize="handleSizeChange"
            >
                <template v-slot:image="slotData">
                    <!-- <img :src="slotData.data.scope.row.image" style="width:100px;height:100px;"> -->
                    <el-image :src="uploadImageUrl+slotData.data.scope.row.image[0].fileName" style="width:100px;height:100px;"
                        :preview-src-list="[uploadImageUrl+slotData.data.scope.row.image[0].fileName]"
                        ref="previewImage"
                    ></el-image>
                </template>
            </QilinTable>
        </el-card>
        <QilinDialog :dialogConfig.sync="dialogConfig" @handleClose="closeDialog"
            @submitConfirm="submitData('formData')" v-drag.draggableX="dragOptions"
        >
            <QilinForm :formConfig.sync="formConfig" ref="formData"></QilinForm>
        </QilinDialog>
        <QilinDialog :dialogConfig.sync="viewDialogConfig" @handleClose="closeViewDialog">
            <QilinView :viewConfig.sync="viewConfig">
            </QilinView>
        </QilinDialog>
    </div>
</template>
<script>

import {
    getImageData,
    insertImageData,
    updateImageData,
    deleteImageData,
    getUserData
} from "@/api/message/index.js";
export default {
    inject:["uploadImageUrl"],
    data(){
        return{
            searchConfig:{
                itemConfig:[
                    {
                        labelName:"选择时间",
                        type:"slot",
                        slotName:"dateRange"
                    }
                ],
                submitData:{
                    startTime:"",
                    endTime:""
                },
                buttonConfig:[
                    {
                        btnName:"添加",
                        type:"primary",
                        size:"small",
                        click:this.insertData
                    }
                ]
            },
            tableConfig:{
                headerConfig:[
                    {
                        label:"序号",
                        type:"sortIndex",
                        width:60
                    },
                    {
                        label:"用户名",
                        prop:"name"
                    },
                    {
                        label:"邮箱",
                        prop:"email"
                    },
                    {
                        label:"图片",
                        prop:"image",
                        type:"slot",
                        slotName:"image",
                        width:150
                    },
                    {
                        label:"日期",
                        prop:"date",
                        width:180,
                        type:"date"
                    },
                    {
                        label:"操作",
                        type:"operate",
                        width:250,
                        operateOptions:[
                            {
                                buttonName:"查看",
                                buttonType:"primary",
                                buttonSize:"mini",
                                buttonEvent:this.viewData
                            },
                            {
                                buttonName:"编辑",
                                buttonType:"warning",
                                buttonSize:"mini",
                                buttonEvent:this.updateData,
                                isDisabled:this.isDisabled
                            },
                            {
                                buttonName:"删除",
                                buttonType:"danger",
                                buttonSize:"mini",
                                buttonEvent:this.deleteData,
                                isDisabled:this.isDisabled
                            }
                        ]
                    }
                ],
                tableData:[],
                paginationsObj:{
                    currentPage:1, //当前页
                    pageSize:5, //当前每页数量
                    pageSizes:[5,10,15], //每页显示多少条选项集
                    total:0, //表格总数量
                    layout:"total,sizes,prev,pager,next,jumper"
                }
            },
            dialogConfig:{ //弹窗的配置对象
                isShow:false,
                title:"添加图片信息"
            },
            formConfig:{
                elFormConfig:{
                    labelWidth:"6.429rem"
                },
                itemConfig:[
                    {
                        dataName:"email",
                        labelName:"邮箱",
                        type:"select",
                        dataListName:"emailList",
                        width:24,
                        change:this.selectEmail,
                        loadMore:this.loadMore,
                        validate:[
                            {
                                type:"email",
                                required:true,
                                message:"请选择用户邮箱",
                                trigger:"change"
                            }
                        ]
                    },
                    {
                        dataName:"name",
                        labelName:"用户名",
                        type:"input",
                        inputType:"text",
                        disabled:true,
                        width:24
                    },
                    {
                        dataName:"image",
                        labelName:"上传图片",
                        type:"uploadImage",
                        showFileList:true,
                        fileList:[],
                        width:24,
                        validate:[
                            {
                                required:true,
                                message:"请上传图片",
                                trigger:"change"
                            }
                        ]
                    }
                ],
                selectLists:{
                    emailList:[]
                },
                submitData:{
                    email:"",
                    name:"",
                    image:""
                }
            },
            currentPage:1, //当前下拉菜单数据第一页
            total:0, //下拉数据的总数目
            viewDialogConfig:{ //查看时的弹窗配置
                isShow:false,
                title:"查看图片信息"
            },
            viewConfig:{
                itemConfig:[
                    {
                        type:"text",
                        label:"用户名",
                        value:"name",
                        col:12
                    },
                    {
                        type:"text",
                        label:"邮箱",
                        value:"email",
                        col:12
                    },
                    {
                        type:"date",
                        label:"日期",
                        value:"date",
                        col:24
                    },
                    {
                        type:"image",
                        label:"图片",
                        value:"image",
                        autoValue:true,
                        col:24
                    }
                ],
                viewData:{
                    name:"",
                    email:"",
                    date:"",
                    image:""
                }
            },
            dragOptions:{
                // container:".el-dialog__wrapper",
                $el:".el-dialog",
                mode:"in",
                left:"30%",
                draggableX:false,
                draggableY:true,
                beforeDrag:(data)=>{
                    // console.log("开始拖拽",data);
                },
                drag:(data)=>{
                    // console.log(data);
                },
                dragged:(data)=>{
                    // console.log("拖拽结束",data);
                },
                ready:(drag)=>{
                    // console.log(drag);
                }
            }
        };
    },
    computed:{
        userInfo(){
            return this.$store.getters.userInfo;
        }
    },
    methods:{
        // 下拉选择滚动加载事件监听
        loadMore(){
            if(this.formConfig.selectLists.emailList.length < this.total){
                this.currentPage++;
                this.getEmailData(this.currentPage,5,"loadmore");
            };
        },
        // 点击关闭查看弹窗事件监听
        closeViewDialog(){
            this.viewDialogConfig.isShow=false;
        },
        // 点击查看按钮事件监听
        viewData(row){
            // console.log(row);
            this.viewConfig.viewData=row;
            this.viewDialogConfig.isShow=true;
        },
        //点击编辑按钮事件监听
        updateData(row){
            // console.log(row);
            this.dialogConfig.title="编辑图片信息";
            this.dialogConfig.isShow=true;
            this.getEmailData();
            this.formConfig.submitData={...row};
            // this.formConfig.itemConfig.forEach((item)=>{
            //     if(item.dataName === "image"){
            //         item.fileList=this.formConfig.submitData.image;
            //     };
            // });
        },
        //点击删除按钮事件监听
        deleteData(row){
            this.$confirm("是否删除此条数据？","提示",{
                showCancelButton:true,
                closeOnClickModal:false,
                type:"warning"
            }).then(()=>{
                deleteImageData(row.id).then((res)=>{
                    if(res.code === 1000){
                        this.$message({
                            message:"删除成功",
                            type:"success"
                        });
                        if(this.tableConfig.tableData.length === 1 && this.tableConfig.paginationsObj.currentPage != 1){
                            this.tableConfig.paginationsObj.currentPage-=1;
                        };
                        this.getTableData();
                        this.$Qilin.Storage.setKeyValueLocalStorage("avatar","moren");
                        this.$store.dispatch("setUserInfo",{...this.userInfo,image:"moren"});
                    };
                });
            }).catch(()=>{
                console.log("取消删除操作");
            });
        },
        // 判断表格按钮是否禁用事件监听
        isDisabled(row,item){
            if(this.userInfo.identify === "manager"){
                return false;
            }else if(this.$Qilin.Storage.getValueLocalStorage("email") === row.email){
                return false;
            }else{
                return true;
            };
        },
        //点击切换页码事件监听
        handleCurrentPage(val){
            // console.log(val);
            this.tableConfig.paginationsObj.currentPage=val;
            this.getTableData();
        },
        //点击切换每页数量事件监听
        handleSizeChange(val){
            // console.log(val);
            this.tableConfig.paginationsObj.pageSize=val;
            this.getTableData();
        },
        //关闭弹窗事件监听
        closeDialog(){
            this.$refs["formData"].formResetFields();
            // 清除已选择的图片
            // this.$refs["uploadImage"].clearFiles();
            this.dialogConfig.isShow=false;
            this.currentPage=1;
        },
        // 点击添加按钮事件监听
        insertData(){
            this.dialogConfig.title="添加图片信息";
            this.dialogConfig.isShow=true;
            this.getEmailData();
            // this.formConfig.itemConfig.forEach((item)=>{
            //     if(item.dataName === "image"){
            //         item.fileList=[];
            //     };
            // });
        },
        // 点击选择邮箱事件监听
        selectEmail(email){
            this.formConfig.submitData.name=this.formConfig.selectLists.emailList.filter((item)=>{
                return item.value == email;
            })[0].name;
        },
        // 上传图片之前的事件监听
        beforeUploadImage(file){
            console.log(file);
        },
        // 关闭图片预览时事件监听
        closePreviewImage(){
            console.log(11);
        },
        // 初始化获取表格内数据
        getTableData(){
            getImageData({
                pageNum:this.tableConfig.paginationsObj.currentPage,
                pageSize:this.tableConfig.paginationsObj.pageSize,
                startTime:this.searchConfig.submitData.startTime,
                endTime:this.searchConfig.submitData.endTime
            }).then((res)=>{
                if(res.code===1000){
                    this.tableConfig.tableData=res.data.data;
                    this.tableConfig.paginationsObj.total=res.data.total;
                };
            });
        },
        // 点击确认按钮事件监听
        submitData(refName){
            this.$refs[refName].formValidate((valid)=>{
                if(valid){
                    // console.log(this.$refs["uploadImage"].uploadFiles[0].raw)
                    if(this.formConfig.submitData.id){ //编辑时进入
                        let fd=new FormData();
                        // 说明编辑了图片--若未编辑图片则没有raw字段，编辑了图片才会有raw字段
                        if(this.formConfig.submitData.image[0].raw){
                            fd.append("image",this.formConfig.submitData.image[0].raw);
                        };
                        fd.append("email",this.formConfig.submitData.email);
                        fd.append("name",this.formConfig.submitData.name);
                        updateImageData(this.formConfig.submitData.id,fd).then((res)=>{
                            if(res.code===1000){
                                this.$message({
                                    message:"编辑用户图片信息成功",
                                    type:"success"
                                });
                                this.closeDialog();
                                this.getTableData();
                                if(res.data.updateImageFileName){
                                    this.$Qilin.Storage.setKeyValueLocalStorage("avatar",res.data.updateImageFileName);
                                    this.$store.dispatch("setUserInfo",{...this.userInfo,image:res.data.updateImageFileName});
                                }
                            };
                        });
                    }else{ //新增时进入
                        let fd=new FormData();
                        fd.append("image",this.formConfig.submitData.image[0].raw);
                        fd.append("email",this.formConfig.submitData.email);
                        fd.append("name",this.formConfig.submitData.name);
                        insertImageData(fd).then((res)=>{
                            if(res.code===1000){
                                this.$message({
                                    message:"添加用户图片信息成功",
                                    type:"success"
                                });
                                this.closeDialog();
                                this.tableConfig.paginationsObj.currentPage=1;
                                this.getTableData();
                                this.$Qilin.Storage.setKeyValueLocalStorage("avatar",res.data.insertImageFileName);
                                this.$store.dispatch("setUserInfo",{...this.userInfo,image:res.data.insertImageFileName});
                            };
                        });
                    };
                };
            });
        },
        // 初始化获取邮箱数据
        getEmailData(pageNum=1,pageSize=5,type){
            getUserData({
                pageNum,
                pageSize
            }).then((res)=>{
                if(res.code===1000){
                    this.total=res.data.total;
                    if(type && type === "loadmore"){
                        if(this.formConfig.selectLists.emailList.length < res.data.total){
                            this.formConfig.selectLists.emailList.push(
                                ...res.data.data.map((item)=>{
                                    return {
                                        value:item.email,
                                        label:item.email,
                                        name:item.name
                                    };
                                })
                            );
                        };
                    }else{
                        this.formConfig.selectLists.emailList=res.data.data.map((item)=>{
                            return {
                                value:item.email,
                                label:item.email,
                                name:item.name
                            };
                        });
                    };
                    this.formConfig.selectLists.emailList.forEach((item)=>{
                        this.tableConfig.tableData.forEach((ite)=>{
                            if(item.label === ite.email){
                                item.disabled=true;
                            };
                        });
                    });
                };
            });
        }
    },
    mounted(){
        this.getTableData();
    }
}
</script>
<style lang="less" scoped>
.qilin-image{
    width:100%;
    padding:0 10px 40px;
    .qilin-QilinSearch{
        .el-form{
            .search-separate{
                margin:0 10px;
            }
        }
    }
}
</style>